package com.jqb.jsplab.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 对FileUpload封装
 */
public class FileUploadTool {
	@SuppressWarnings("unused")
	private HttpServletRequest request = null;
	/**
	 * 存放上传的所有内容
	 */
	private List<FileItem> items = null;
	/**
	 * 存放普通字段信息:name-values
	 */
	private Map<String, List<String>> params = new HashMap<String, List<String>>();
	/**
	 * 存放文件字段信息:filename-value
	 */
	private Map<String, FileItem> files = new HashMap<String, FileItem>();

	/**
	 * 构造函数传入Request,文件大小,临时目录
	 * @param request
	 * @param maxSize
	 * @param tmpDir
	 * @throws Exception
	 */
	public FileUploadTool(HttpServletRequest request, int maxSize, String tmpDir)
			throws Exception {
		this.request = request;
		/**
		 * 创建磁盘工厂
		 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		if (tmpDir != null) {
			factory.setRepository(new File(tmpDir));
		}
		/**
		 * 创建文件上传处理类
		 */
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		if (maxSize > 0) {
			upload.setFileSizeMax(maxSize);
		}
		/**
		 * 获取全部上传内容
		 */
		this.items = (List<FileItem>)upload.parseRequest(request);
		this.init();
	}

	/**
	 * 初始化
	 */
	private void init() {
		/**
		 * 循环处理所有上传内容
		 */
		Iterator<FileItem> iter = this.items.iterator();
		/**
		 * 重命名
		 */
		Rename re = new Rename("192.168.1.1");
//		Rename re = new Rename(request.getRemoteAddr());
		
		while (iter.hasNext()) {
			FileItem item = iter.next();
			/**
			 * 普通字段
			 */
			if (item.isFormField()) {
				String fieldName = item.getFieldName();
				String value = item.getString();
				List<String> tmpList = null;
				if (this.params.containsKey(fieldName)) {
					tmpList=this.params.get(fieldName);
				}else{
					tmpList = new ArrayList<String>();
				}
				tmpList.add(value);
				this.params.put(fieldName, tmpList);
			} else {
				/**
				 * 文件字段
				 */
				String ext[]=item.getName().split("\\.");
				if(ext.length>1){
					String fileName=re.getNewName()+"."+ext[1];
					this.files.put(fileName, item);
				}
			}
		}
	}
	/**
	 * 返回一个普通字段的单个值
	 * @param name
	 * @return
	 */
	public String getParameter(String name){
		String ret=null;
		List<String> tmp=this.params.get(name);
		if(tmp!=null){
			ret=tmp.get(0);
		}
		return ret;
	}
	/**
	 * 返回一个普通字段的多个值
	 * @param name
	 * @return
	 */
	public String[] getParameterValues(String name){
		String ret[]=null;
		List<String> tmp=this.params.get(name);
		if(tmp!=null){
			ret=tmp.toArray(new String[]{});
		}
		return ret;
	}
	/**
	 * 返回文件字段信息的Map
	 * @return
	 */
	public Map<String,FileItem> getUploadFiles(){
		return this.files;
	}
	
	/**
	 * 保存文件
	 * @param saveDir
	 * @return
	 * @throws IOException
	 */
	public List<String> saveAll(String saveDir) throws IOException{
		
		List<String> names=new ArrayList<String>();
		
		if(this.files.size()>0){
			
			File saveFile = null;
			InputStream input = null;
			OutputStream output = null;
			
			Set<String> keys=this.files.keySet();
			Iterator<String> iter=keys.iterator();
			
			while(iter.hasNext()){
				
				String fileName=iter.next();
				saveFile=new File(saveDir+fileName);
				names.add(fileName);
				
				FileItem item= this.files.get(fileName);
				input = item.getInputStream();
				output = new FileOutputStream(saveFile);

				int len=0;
				byte data[] = new byte[512];
				while((len=input.read(data))!=-1){
					output.write(data,0,len);
				}
			}
			input.close();
			output.close();
		}
		
		return names;
		
	}
}






























